<script setup>
import {onMounted, ref} from "vue";
import {homePageQueryArticle} from "@/api/api.js";
import useClipboard from "vue-clipboard3";
import jing from "./../assets/jing.png"
import router from "@/modules/router.js";
import {showConfirmDialog, showFailToast, showSuccessToast} from "vant";
import {getResetToken, getToken} from "@/utils/auth.js";


const pageNo = ref(0)
const articleList = ref([])
const show = ref(false);
const checked = ref(false);
const startTime = ref("开始日期");
const endTime = ref("结束日期");
const showLeft = ref(false);
const minDate = new Date(2010, 0, 1); // 设置最小日期为2010年1月1日
const maxDate = new Date(); // 设置最大日期为当前日期
const showTop = ref(false)
const tagList = ref([
    {label: "Media buy", id: "1"},
    {label: "实操案例", id: "1"},
    {label: "有点译思", id: "1"},
    {label: "资源分享", id: "1"},
    {label: "经验之谈", id: "1"},
    {label: "大家支招", id: "1"},
    {label: "大航海计划", id: "1"},
    {label: "跨境电商", id: "1"},
    {label: "转载干活", id: "1"},
    {label: "YouTube赚钱", id: "1"},
    {label: "讨论一下", id: "1"},
    {label: "我要赚美金", id: "1"},
    {label: "大咖说", id: "1"},
    {label: "SEO", id: "1"},
    {label: "亚马逊", id: "1"},
]);
const resetToken = ref('')
const copyResetToken = async (value)=>{
  const values = `重置码:${value}`
  const { toClipboard } = useClipboard();
    try {
      await toClipboard(values);  //实现复制
      showSuccessToast("复制成功");
    } catch (e) {
      showFailToast(e)
    }
  showTop.value = false
}
const copyToken = (value)=>{
  copyResetToken(value)
  setTimeout(()=>{
    window.location.href = 'weixin://';
  },1000)
}
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
};
const onConfirm = (values) => {
    console.log(values);
    const [start, end] = values;
    show.value = false;
    startTime.value = formatDate(start);
    endTime.value = formatDate(end);
};
const checkedChange = () => {
  articleList.value = []
  refreshing.value = true;
  loading.value = true;
  pageNo.value = 0
  getHomePageQueryArticle()
}
const refreshing = ref(false)

const loading = ref(false)

const finished = ref(false)

const onRefresh = () => {
  refreshing.value = true;
  loading.value = true;
  pageNo.value = 0
  getHomePageQueryArticle();
};
const getHomePageQueryArticle = () => {
  pageNo.value = pageNo.value + 1
  let query = {}
  if(checked.value){
    query = {
      pageNo: pageNo.value,
      pageSize: 10,
      digested: 1
    }
  }else{
    query = {
      pageNo: pageNo.value,
      pageSize: 10,
    }
  }
  homePageQueryArticle(query).then(res => {
    if (pageNo.value == 1) {
      articleList.value = []
      articleList.value = res.result.records
    } else {
      articleList.value.push(...res.result.records)
    }
    if (articleList.value.length == res.result.total) {
      finished.value = true
    }
  }).finally(() => {
    refreshing.value = false
    loading.value = false
  })
}

const toTag = (val) => {
  router.push({
    path: "/tagPage",
    query: {
      tag: val
    }
  })
}

const toSearch = () => {
  router.push({
    path: '/search'
  })
}

const toLogin = () => {
  router.push({
    path: '/login'
  })
}
onMounted(() => {
  resetToken.value = getResetToken()||''
  if (router.currentRoute.value.query.id) {
    showTop.value = true
    router.push({ path: '/' });
  }
})
const showResetTokenDialog = ()=>{
  const resetToken =
  showConfirmDialog({
    title: '重要提示',
    message:
        '如果解决方法是丑陋的，那就肯定还有更好的解决方法，只是还没有发现而已。',
  })
      .then(() => {
        // on confirm
      })
      .catch(() => {
        // on cancel
      });
}
</script>

<template>
  <van-dialog
      v-model:show="showTop"
      width="40%"
      title="重要提示"
      show-cancel-button
      confirm-button-text="复制重置码并打开微信"
      @confirm="copyToken(resetToken)"
  >
    <div class="p-5">
      <div >您的重置码为:</div>
      <van-text-ellipsis :content="resetToken" expand-text="展开" collapse-text="收起" />
      <span>点击下方按钮复制重置码并打开微信发送给自己保存</span>
    </div>
  </van-dialog>

  <van-calendar
      v-model:show="show"
      :max-date="maxDate"
      :min-date="minDate"
      type="range"
      @confirm="onConfirm"
  />
  <van-sticky>
    <div class="header">
      <van-icon name="wap-nav" size="30" @click="showLeft = true"/>
            <div>
              {{articleList != null && articleList.length > 0?articleList[0].groupInfo.name:''}}
            </div>
<!--      <div class="timeBox" @click="show = true">-->
<!--        <div class="time">{{ startTime }}</div>-->
<!--        <div>&ndash;&gt;</div>-->
<!--        <div class="time">{{ endTime }}</div>-->
<!--        <div class="iconTime">-->
<!--          <van-icon name="notes-o" size="18"/>-->
<!--        </div>-->
<!--      </div>-->
      <van-switch v-model="checked" @change="checkedChange">
        <template #node>
          <div class="icon-wrapper">
            <van-icon
                :name="
              checked
                ? jing
                : ''
            "
            ></van-icon>
          </div>
        </template>
      </van-switch>
    </div>
  </van-sticky>
  <div class="content-card-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="getHomePageQueryArticle"
      >
        <share-card v-for="(item, index) in articleList" :key="index" :item="item"></share-card>
      </van-list>
    </van-pull-refresh>

  </div>
  <!-- 左侧弹出 -->
  <van-popup
      v-model:show="showLeft"
      :style="{ width: '25%', height: '100%' }"
      position="left"
  >
    <van-icon
        class="popupClose"
        name="cross"
        size="25"
        @click="showLeft = false"
    />
    <div class="popupGrid">
<!--      <van-grid :border="false" :column-num="5">-->
<!--        <van-grid-item icon="apps-o" text="最新实战" to="/latestActualCombat"/>-->
<!--        <van-grid-item icon="aim" text="往期实战" to="/pastCombat"/>-->
<!--        <van-grid-item badge="99+" icon="user-o" text="关注" to="/focus"/>-->
<!--        <van-grid-item-->
<!--            badge="99+"-->
<!--            icon="good-job-o"-->
<!--            text="收藏"-->
<!--            to="/collect"-->
<!--        />-->
<!--        <van-grid-item-->
<!--            badge="99+"-->
<!--            icon="underway-o"-->
<!--            text="历史"-->
<!--            to="/history"-->
<!--        />-->
<!--      </van-grid>-->
    </div>
    <van-divider
        :style="{ color: '#000', borderColor: '#cfcfcf', 'font-size': '20px' }"
    >
      导航栏
    </van-divider>
    <div class="tags">
      <van-tag
          v-for="(item, index) in tagList"
          :key="index"
          plain
          round
          size="large"
          style="margin: 10px 10px 0 0;color: #107459;border-color: #c5c6cb;"
          type="primary"
          @click="toTag(item.label)"
      >{{ item.label }}
      </van-tag
      >
      <van-button plain round size="small" style="width: 100%; margin-top: 20px" @click="toSearch"
      >星球内容索引工具
      </van-button
      >
      <van-button plain round size="small" style="width: 100%; margin-top: 10px" @click="toLogin"
      >输入新的注册码
      </van-button
      >
      <div class="mt-10 reset-token">
        <div>重置码:</div>
        <div class="token">{{ resetToken }}</div>
        <van-button type="primary" size="mini" @click="copyResetToken(resetToken)">复制</van-button>
      </div>

    </div>
  </van-popup>
</template>

<style scoped>
.tags {
  display: flex;
  flex-wrap: wrap;
  padding: 20px;
}

.popupGrid {
  margin-top: 40px;
}

.popupClose {
  float: right;
  padding: 5px;
}

.time {
  width: 75px;
  text-align: center;
}

.iconTime {
  margin-right: 5px;
}

.timeBox {
  width: 240px;
  border: 1px solid #cfcfcf;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-radius: 5px;
  font-size: 14px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 10px;
  border-bottom: 1px solid #cfcfcf;
  background: #ffffff;
  border-radius: 10px;
  width: 837px;
  margin: auto;
}

.content-card-list {
  background: #f2f5f9;
  max-width: 837px;
  margin:auto;
}
</style>
<style>
.icon-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}
.reset-token{
  display: flex;
  flex-direction: row;
}
.token{

  flex: 1;
  max-width: 30%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.van-switch--on {
  background: #107459;
}
</style>
